package com.glodon.paas.job.agent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.UnknownHostException;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFileOutputStream;

public class BatchDeploy {
    public static void main(String[] args) throws IOException {
        for (String arg : args) {
            String[] params = arg.split(",");
            String url = params[0];
            String file = params[1];
            deploy(url, file);
        }
    }

    private static void deploy(String url, String file) throws FileNotFoundException, SmbException,
            MalformedURLException, UnknownHostException, IOException {
        System.out.println("deploy to " + url + ", file: " + file);
        FileInputStream is = new FileInputStream(file);
        SmbFileOutputStream os = new SmbFileOutputStream(url);
        long length = new File(file).length();
        byte[] buf = new byte[(int) Math.max(length / 100, 100 * 1024)];
        copy(is, os, buf, length);
        System.out.println("deploy success");
        os.close();
        is.close();
    }

    public static long copy(InputStream input, OutputStream output, byte[] buffer, long length) throws IOException {
        long count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            System.out.println("progress: " + count * 100 / length + "%");
            count += n;
        }
        return count;
    }
}
